package logic

import (
	"context"
	"fmt"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/goods"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

type OrderLogicGoods struct {
	Repetition        bool
	TradeNo           string
	Amount            int
	Err               error
	AddGoodsOrderList []*goods.OrderUpdate
}

// NewOrderLogicGoods 生成商品订单
func NewOrderLogicGoods(param *request.CreateStewardOrderReq, tradeNo string) *OrderLogicGoods {
	RdbKey := fmt.Sprintf("good-order-%d-%d", param.PlaceId, param.UserId)
	if t := global.Rdb.TTL(context.Background(), RdbKey).Val(); t > 0 {
		return &OrderLogicGoods{Repetition: true}
	}

	global.Rdb.Set(context.Background(), RdbKey, param.GoodsList, time.Second*10)
	return &OrderLogicGoods{TradeNo: tradeNo}
}

// InsertOrdersLogicGoods 批量写入订单
func (logic *OrderLogicGoods) InsertOrdersLogicGoods(param *request.CreateStewardOrderReq) {
	var goodIds []int
	goodIdMap := map[int]int{}
	var insertListDb []*goods.OrderUpdate

	placeInfo := dao.NewPlaceDao().GetPlaceInfoByDeviceSnANDid(param.DeviceSn, param.PlaceId).Unwrap().(*devices.DeviceANDIdWithPlaceInfo)
	if placeInfo.Id == 0 {
		return
	}

	for _, item := range param.GoodsList {
		goodIdMap[item.Id] = item.Num
		goodIds = append(goodIds, item.Id)
	}
	goodsList := dao.NewGoodsDao().GetGoodsByIds(goodIds)
	if len(goodIds) != len(goodsList) {
		return
	}

	for _, item := range goodsList {
		amount := (item.Price - item.DiscountAmount) * goodIdMap[item.Id]
		logic.Amount += utils.IfTrueInt(amount >= 0, amount, 0)
		insertListDb = append(insertListDb, &goods.OrderUpdate{
			MemberId:     param.UserId,
			PlaceId:      param.PlaceId,
			Message:      param.Message,
			GoodsId:      item.Id,
			TradeNo:      logic.TradeNo,
			Status:       helper.TypeNumGoodsOrderStatusWait,
			PayType:      2,
			BuyNum:       goodIdMap[item.Id],
			Price:        item.Price,
			Amount:       amount,
			UserId:       placeInfo.UserID,
			PlaceName:    placeInfo.PlaceName,
			PlaceAddress: placeInfo.Address,
			Address:      placeInfo.Room,
			DeviceSn:     param.DeviceSn,
		})
	}

	logic.AddGoodsOrderList, logic.Err = dao.NewGoodsDao().InsertGoodsOrders(insertListDb)
}
